import { login, loginByPhone } from '@/services/loginApi';
import { encryptWithSHA256 } from '@/utils/crypto';
import { AlipayCircleOutlined, LockOutlined, MobileOutlined, TaobaoCircleOutlined, UserOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { LoginFormPage, ProConfigProvider, ProFormText, ProFormCaptcha, ProFormCheckbox, setAlpha } from '@ant-design/pro-components';
import { history, useModel, useRequest } from '@umijs/max';
import { Button, Divider, GlobalToken, message, theme, Space, Tabs, Form } from 'antd';
import { setCookie } from '@/utils/cookieUtils';
import { useState, CSSProperties } from 'react';
import { request } from '@umijs/max';

const getActivityConfig = (token: GlobalToken) => {
  return {
    style: {
      boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
      color: token.colorTextHeading,
      borderRadius: 8,
      backgroundColor: 'rgba(255,255,255,0.25)',
      backdropFilter: 'blur(4px)',
    },
    title: '活动标题，可配置图片',
    subTitle: '活动介绍说明文字',
    action: (
      <Button
        size="large"
        style={{
          borderRadius: 20,
          background: token.colorBgElevated,
          color: token.colorPrimary,
          width: 120,
        }}
      >
        去看看
      </Button>
    ),
  };
};

type LoginType = 'phone' | 'account';

const LoginPage = () => {
  const { token } = theme.useToken();
  const { initialState, refresh } = useModel('@@initialState');
  const [loginType, setLoginType] = useState<LoginType>('account');
  const [form] = Form.useForm();

  const iconStyles: CSSProperties = {
    marginInlineStart: '16px',
    color: setAlpha(token.colorTextBase, 0.2),
    fontSize: '24px',
    verticalAlign: 'middle',
    cursor: 'pointer',
  };

  const requestLoginByPhone = useRequest(loginByPhone,{
    manual: true,
    loadingDelay: 1000,
    onSuccess: async (data) => {
      if (data && data.token) {
        // 保存token到cookie，设置7天过期
        setCookie('token', data.token, 7);
        
        // 登录成功后获取用户信息
        try {
          // 刷新全局初始状态
          await refresh();
          history.replace('/dashboard');
        } catch (error) {
          console.error('获取用户信息失败:', error);
          history.replace('/dashboard');
        }
      } else {
      }
    },
    onError: (error) => {
      console.error('登录失败:', error);
    },
  })

  const requestLogin = useRequest(login, {
    manual: true,
    loadingDelay: 1000,
    onSuccess: async (data) => {
      if (data && data.token) {
        // 保存token到cookie，设置7天过期
        setCookie('token', data.token, 7);
        
        // 登录成功后获取用户信息
        try {
          // 刷新全局初始状态
          await refresh();
          history.replace('/dashboard');
        } catch (error) {
          console.error('获取用户信息失败:', error);
          history.replace('/dashboard');
        }
      } 
    },
    onError: (error) => {
      console.error('登录失败:', error);
    },
  });

  return (
    <div style={{ height: '100vh' }}>
      <LoginFormPage
        form={form}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="书院小管家"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="书院小管家后台管理系统"
        activityConfig={getActivityConfig(token)}
        actions={
          <div>
            <Divider plain>
              <span
                style={{
                  color: token.colorTextPlaceholder,
                  fontWeight: 'normal',
                  fontSize: 14,
                }}
              >
                忘记密码？请联系管理员
              </span>
            </Divider>
          </div>
        }
        onFinish={async (values) => {
          try {
            let loginParams: any;
            if (loginType === 'account') {
              // 对密码进行SHA-256加密
              const encryptedPassword = encryptWithSHA256(values.password);
              loginParams = {
                username: values.account,
                password: encryptedPassword
              };
              // 发送登录请求
              await requestLogin.run(loginParams);
            } else {
              loginParams = {
                phone: values.mobile,
                smsCode: values.captcha
              };

              await requestLoginByPhone.run(loginParams)
            }
            return true;
          } catch (error) {
            console.error('登录过程出错:', error);
            message.error('登录失败，请重试');
            return false;
          }
        }}
      >
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
        >
          <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
          <Tabs.TabPane key={'phone'} tab={'手机号登录'} />
        </Tabs>
        {loginType === 'account' && (
          <>
            <ProFormText
              name="account"
              width="md"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder={'账号'}
              rules={[
                {
                  required: true,
                  message: '请输入账号!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              width="md"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}
        {loginType === 'phone' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={'prefixIcon'} />,
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                try {
            // 发送获取验证码请求
            const response = await request('/api/auth/sendSmsCode', {
              method: 'POST',
              data: {
                phone: form.getFieldValue('mobile'),
              },
            });
            if (response.code === 200) {
              message.success('获取验证码成功！');
            } else {
              message.error(response.message || '获取验证码失败');
            }
                } catch (error) {
                  console.error('获取验证码出错:', error);
                  message.error('获取验证码失败，请重试');
                }
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <LoginPage />
    </ProConfigProvider>
  );
};
